var createError = require('http-errors');  
var express = require('express');
var path = require('path');
var morgan = require('morgan');
const {secretkey } = require("./utils/jwt")

var app = express();
// var cookieParser = require('cookie-parser');
const {expressjwt} = require('express-jwt')
app.use(expressjwt({
  secret:secretkey,
  algorithms:["HS256"]

}).unless({
  path:[
    "/users",
    // /^\/articles\/users\/[a-zA-Z0-9]+$/
  ]
}))
 

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/user');
var articlesRouter = require('./routes/articles');
var uploadsRouter = require('./routes/upload');


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//正则匹配
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/articles', articlesRouter);
app.use('/uploads', uploadsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  if(err.name == 'UnauthorizedError'){
    res.send({"msg":"未授权"});
  }else{
    res.send({"msg":err.message});
  }
});

module.exports = app;
